<template>
    <div class="patient-management">
        <!-- 搜索栏 -->
        <header class="fixed-header">
            <div class="search-bar">
                <el-input v-model="searchQuery" placeholder="请输入患者姓名或病历号" clearable @clear="handleSearch"
                    @keyup.enter="handleSearch">
                    <template #append>
                        <el-button :icon="Search" @click="handleSearch" />
                    </template>
                </el-input>
                <el-button type="primary" :icon="Plus" @click="handleAddPatient">新增患者</el-button>
            </div>
        </header>

        <!-- 患者列表 -->
        <Main class="scroll-area">
            <el-table :data="filteredPatients" stripe style="width: 100%" @row-click="handleRowClick">
                <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                    :sortable="column.sortable" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button style="margin-left: 20px;"
                            @click="routerPush('Registration', scope.row)">挂号</el-button>
                        <el-button type="link" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="link" :icon="Delete"
                            @click.stop="isDeleteDialog = true, patient = scope.row">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </Main>


        <!-- 分页 -->
        <footer class="fixed-footer">
            <div class="pagination-wrap">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalPatients"
                    layout="total, sizes, prev, pager, next, jumper" @current-change="handlePageChange" />
            </div>
        </footer>

        <!-- 患者详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="患者详情" size="40%">
            <div v-if="selectedPatient">
                <h3>{{ selectedPatient.name }} 的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="姓名">{{ selectedPatient.name }}</el-descriptions-item>
                    <el-descriptions-item label="性别">{{ selectedPatient.gender }}</el-descriptions-item>
                    <el-descriptions-item label="年龄">{{ selectedPatient.age }}</el-descriptions-item>
                    <el-descriptions-item label="手机号码">{{ selectedPatient.contactPhone }}</el-descriptions-item>
                    <el-descriptions-item label="住址">{{ selectedPatient.address }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号">{{ selectedPatient.idNumber }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>

        <!-- 新增/编辑患者对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑患者' : '新增患者'">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="男" />
                        <el-radio label="女" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="form.age" />
                    <!-- <el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" /> -->
                </el-form-item>
                <el-form-item label="手机号码" prop="contactPhone">
                    <el-input v-model="form.contactPhone" onkeypress="return /[0-9]/i.test(event.key)" maxlength="11" />
                </el-form-item>
                <el-form-item label="身份证号码" prop="address">
                    <el-input v-model="form.idNumber" />
                </el-form-item>
                <el-form-item label="住址" prop="address">
                    <el-input v-model="form.address" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
        <el-dialog title="确认操作" v-model:="isDeleteDialog" width="30%" @confirm="handleDelete" @close="handleClose">
            <p>您确定要执行此操作吗？</p>
            <template #footer>
                <el-button @click="handleClose">否</el-button>
                <el-button type="primary" @click.stop="handleDelete(patient.id)">是</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { PostPatient, DeletePatient, GetPatients, PutPatient } from '@/api/patientService'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router';
import { usePatientStore } from '@/utils/stores/patient';

const store = usePatientStore()
const router = useRouter()

const patient = ref<any>()

const routerPush = (path: string, patient: any) => {
    store.patient = patient
    router.push(path)
}

const { t } = useI18n()

const columns = [
    { prop: 'name', label: '姓名', sortable: true },
    { prop: 'age', label: '年龄', sortable: true },
    { prop: 'contactPhone', label: '手机号码', sortable: true },
    { prop: 'idNumber', label: '身份证号码', sortable: true },
    { prop: 'gender', label: '性别', sortable: true },
    { prop: 'address', label: '住址' }
]

// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: t('cannotBlank', { field: t('name') }), trigger: 'blur' },
        { min: 2, max: 20, message: '患者姓名长度应为 2 到 20 个字符', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: t('cannotBlank', { field: t('gender') }), trigger: 'blur' },
    ],
    age: [
        { required: true, message: t('cannotBlank', { field: t('age') }), trigger: 'blur' },
        { min: 0, message: '年龄应该大于0', trigger: 'blur' }
    ],
    idNumber: [
        { required: true, message: t('cannotBlank', { field: t('idNumber') }), trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                    callback(new Error('请输入有效的身份证号码'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    contactPhone: [
        { required: true, message: t('cannotBlank', { field: t('contactPhone') }), trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!/^1[3-9]\d{9}$/.test(value)) {
                    callback(new Error('请输入有效的中国大陆手机号码'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    address: [
        { required: true, message: t('cannotBlank', { field: t('address') }), trigger: 'blur' },
    ]
})

const patients = ref<any>([])
onMounted(async () => {
    const response = await GetPatients()
    patients.value = response.data
    console.log(patients)
})

// 搜索功能
const searchQuery = ref('')
const filteredPatients = computed(() => {
    return patients.value.filter(patient =>
        patient.name.includes(searchQuery.value)
        // patient.idNumber.includes(searchQuery.value)
    )
})

// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalPatients = computed(() => filteredPatients.value.length)

// 患者详情
const drawerVisible = ref(false)
const selectedPatient = ref<any>(null)

// 新增/编辑患者
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref<any>({
    id: 0,
    name: "",
    idNumber: "",
    gender: "",
    age: null,
    contactPhone: "",
    address: "",
})

// 方法
const handleSearch = () => {
    currentPage.value = 1
}

const handleRowClick = (patient) => {
    selectedPatient.value = patient
    drawerVisible.value = true
}

const handleAddPatient = () => {
    form.value = {
        id: 0,
        name: "",
        idNumber: "",
        gender: "",
        age: null,
        contactPhone: "",
        address: "",
    }
    isEdit.value = false
    dialogVisible.value = true
}

const handleEdit = (patient: any) => {
    // form.value = { ...patient }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = {
        id: patient.id,
        name: patient.name,
        idNumber: patient.idNumber,
        gender: patient.gender,
        age: patient.age,
        contactPhone: patient.contactPhone,
        address: patient.address,
    }
    isEdit.value = true
    dialogVisible.value = true
}

const formRef = ref<any>(null)

const handleSubmit = () => {
    const request = {
        id: form.value.id,
        name: form.value.name,
        idNumber: form.value.idNumber,
        gender: form.value.gender,
        age: form.value.age,
        contactPhone: form.value.contactPhone,
        address: form.value.address,
    }
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = patients.value.findIndex(p => p.id === request.id)
                patients.value[index] = { ...request }
                // PatchPatientApi(form.value.id, form.value)
                PutPatient(request.id, request)
                console.log('编辑患者:', request)
            } else {
                patients.value.push({ ...request, id: patients.value.length + 1 })
                PostPatient(request)
                console.log('新增患者:', request)
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })

}

const handlePageChange = (page) => {
    currentPage.value = page
}

const handleDelete = (id: number) => {
    console.log('用户选择了「是」')
    patients.value = patients.value.filter(p => p.id !== id)
    DeletePatient(id)
    // 执行确认操作
    isDeleteDialog.value = false
}

const isDeleteDialog = ref(false)

const handleClose = () => {
    console.log('用户选择了「否」')
    isDeleteDialog.value = false
}
</script>

<style scoped>
.patient-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination-wrap {
    margin-top: 20px;
    text-align: right;
}

.el-input__inner[type="tel"] {
    letter-spacing: 0.2em;
}

.fixed-top {
    position: sticky;
    top: 0;
}

.fixed-bottom {
    position: sticky;
    bottom: 0;
}

.el-button--link {
    background: transparent;
    border: 0cap;
    text-decoration: none;
}
</style>